package com.jd.sentinelspringboot.apollo;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.InitializingBean;

import java.util.List;


public class ApolloDataSorceListener implements InitializingBean {

    private static  final String FLOW_RULE_TYPE="flow";
    // *-flow-rules
    private static  final String FLOW_DATA_ID_POSTFIX="-"+FLOW_RULE_TYPE+"-rules";

    private static  final String NAME_SPACE="application";

    private String applicationName;

    public ApolloDataSorceListener(String applicationName){
        this.applicationName=applicationName;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        initFlowRules();
    }

    public  void initFlowRules(){
        //感兴趣的key
        String flowRuleKey=applicationName+FLOW_DATA_ID_POSTFIX;
        //动态监听
        ReadableDataSource<String,List<FlowRule>> flowRuleDatasource=new ApolloDataSource<>(NAME_SPACE,
                flowRuleKey,
                "[]",
                source-> JSON.parseObject(source,new TypeReference<List<FlowRule>>(){}));
        //规则管理器、刷新到内存
        FlowRuleManager.register2Property(flowRuleDatasource.getProperty());
    }


    //     List<FlowRule> rules = new ArrayList<FlowRule>();
//        FlowRule rule = new FlowRule();
//        //注意： 我们的规则一定要绑定到对应的资源上，通过资源名称进行绑定
//        rule.setResource("HelloWorld");
//        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        // Set limit QPS to 20.
//        rule.setCount(20);
//        rules.add(rule);
//        //规则管理器
//        FlowRuleManager.loadRules(rules);
}
